package com.heima.reggie.security;

import com.alibaba.fastjson.JSON;
import com.heima.reggie.bean.Employee;
import com.heima.reggie.bean.User;
import com.heima.reggie.common.R;
import com.heima.reggie.filter.LoginFilter2;
import com.heima.reggie.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private EmployeeDetailsServiceImpl es;

    @Bean
    public BCryptPasswordEncoder bcr(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //使用数据库认证方式
        auth.userDetailsService(es);
    }


    @Bean
    public LoginFilter2 loginFilter02 () throws Exception {
        LoginFilter2 filter = new LoginFilter2();
        //设置认证管理员
        filter.setAuthenticationManager(authenticationManagerBean());
        //设置登录执行的请求
        filter.setFilterProcessesUrl("/employee/login");
        //设置登录成功处理办法
        filter.setAuthenticationSuccessHandler((req,resp,auth)->{
            Employee e = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println("-----------------");
            System.out.println(e);
            String json = JSON.toJSONString(R.success(e));
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(json);
        });
        //设置登录失败处理办法
        filter.setAuthenticationFailureHandler((req, resp ,ex)->{
            resp.setContentType("application/json;charset=utf-8");
            String json = JSON.toJSONString(R.error("登录失败"));
            resp.getWriter().write(json);
        });
        return filter;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/backend/page/login/login.html").permitAll()
                .and().logout().logoutUrl("/logout")
                .logoutSuccessHandler((req, resp , auth) ->{
                    String json = JSON.toJSONString(R.success("退出登录成功"));
                    resp.getWriter().write(json);
                })
                .and().authorizeRequests()
                .antMatchers("/**/*.js" , "/**/*.css" , "/**/styles/**","/sms/code" , "/**/*.ico" , "/**/images/**",
                        "/**/login.html","/user/**","/front/**","/**/list","/common/**","/doc.html,","/webjars/**","/swagger-resources","/v2/api-docs").permitAll()
                .anyRequest().authenticated()
                .and().headers().frameOptions().sameOrigin() //加入同源策略，这样即可允许页面上加载iframe子页面
                .and().csrf().disable();


        http.addFilterAt(loginFilter02() , UsernamePasswordAuthenticationFilter.class);
    }
}
